#include <iostream>
#include <fstream>
using namespace std;
#include "contacts.pb.h"
void AddPeopleInfo(contacts2::PeopleInfo* people)
{
    cout<<"-------------新增联系⼈-------------"<<endl;
    cout<<"请输⼊联系⼈姓名: ";
    string name;
    getline(cin,name);
    people->set_name(name);
    cout<<"请输⼊联系人生日: ";
    int birthday;
    cin>>birthday;
    people->set_birthday(birthday);
    cin.ignore(256,'\n');//清空缓冲区的\n
    
    for(int i = 0;;i++)
    {
        cout<<"请输⼊联系⼈电话"<<i+1<<": ";
        string number;
        getline(cin,number);
        if(number=="")
            break; 
        contacts2::PeopleInfo_Phone* phone = people->add_phone();
        phone->set_number(number);

    }

    cout<<"-----------添加联系⼈成功-----------"<<endl;
}
int main()
{
    contacts2::Contacts contacts;
    //打开文件，读取通讯录的信息
    fstream input("../contacts.bin",ios::in | ios::binary);//因为文件中存储的是二进制的信息
    if(!input)
    {
        cout<<"contacts.bin not find , create a new file"<<endl;
    }
    else if(!contacts.ParseFromIstream(&input))
    {
        cerr<<"parse error"<<endl;
        input.close();
        return -1;
    }
    //添加信息
    AddPeopleInfo(contacts.add_people());
    //将信息写入文件
    fstream output("../contacts.bin",ios::out | ios::trunc |ios::binary);//覆盖写因为上面已经将通讯录中的信息读出来了。
    if(!contacts.SerializeToOstream(&output))
    {
        cerr<<"write error"<<endl;
        output.close();
        input.close();
        return -2;
    }
    cout<<"write success"<<endl;
    output.close();
    input.close();
    return 0;
}